import 'package:dio/dio.dart';
import 'package:mi_mang_flutter/network/extra_keys.dart';
import '../model/public/oauth_model.dart';
import '../model/public/entity_factory.dart';
import '../network/response_data.dart';
import '../config/configs.dart';
import '../network/client.dart' as http;

/// oauth2.0 获取token, 刷新token相关接口
const String _API_OAUTH_TOKEN = '/api/oauth/token';
const String _API_REFRESH_TOKEN = '/api/oauth/token';

/// 获取token
Future<ResponseData<OAuthModel>> login(String username, String password) async {
  var response = await http.client.tokenPost(
    _API_OAUTH_TOKEN,
    queryParameters: {
      'client_id': Configs.CLIENT_ID,
      'client_secret': Configs.CLIENT_SECRET,
      'grant_type': 'password',
      'username': username,
      'password': password,
    },
    options: Options(extra: {
      ExtraKeys.NEED_LOADING: true,
      ExtraKeys.NEED_LOADING_MSG: "正在登录...",
    }),
  );
  return ResponseData<OAuthModel>(
    code: response.code,
    msg: response.msg,
    data: EntityFactory.generateOBJ(response.data),
  );
}

/// 刷新token
Future<ResponseData> refreshToken(String? refreshToken) {
  return http.client.tokenPost(
    _API_REFRESH_TOKEN,
    queryParameters: {
      'client_id': Configs.CLIENT_ID,
      'client_secret': Configs.CLIENT_SECRET,
      'grant_type': "refresh_token",
      'refresh_token': refreshToken,
    },
  );
}

/// 短信验证码登录
///
/// [phone]电话号码
///
/// [vCode]验证码
Future<ResponseData<OAuthModel>> loginBySMS(String phone, String vCode) async {
  var response = await http.client.tokenPost(
    _API_OAUTH_TOKEN,
    queryParameters: {
      'client_id': Configs.CLIENT_ID,
      'client_secret': Configs.CLIENT_SECRET,
      'grant_type': 'password',
      'phone_number': phone,
      'password': vCode,
      'auth_type': 'sms',
    },
    options: Options(extra: const {ExtraKeys.NEED_TOAST: true}),
  );
  return ResponseData<OAuthModel>(
    code: response.code,
    msg: response.msg,
    data: EntityFactory.generateOBJ(response.data),
  );
}
